import searchView from '../views/search.art'
import listsView from '../views/lists.art'
import notfoundView from '../views/notfound.art'
import searchModel from '../models/search'

class Search {
    constructor(){
        this.list = [];
        this.total =0;
    }
    renderer({list,total}){  //关于图片的转换
        this.arr = []
        this.total =[total]
        for(let i=0;i<list.length;i++){
            this.arr.push(list[i].img.replace('w.h','128.180'));
        }
        let listsViewHtml = listsView({
            list,
            total:this.total,
            arr:this.arr
        })
        $('ul .list').html(listsViewHtml)
    }
    render(){

        let that = this
        let searchViewHtml = searchView()
        $('#root').html(searchViewHtml)
        let timer=null;

        $('input').on('input', function(){
            if($('input').val()==''){
                clearTimeout(timer)
                $('ul .list').html('');
            }else{
                clearTimeout(timer)
                $('.cancel1').css('display','inline-block')
                timer=setTimeout(async function(){
                    let result = await searchModel.get({
                        kw: $('input').val(),
                        cityId : localStorage.getItem('cityId') ||('1')
                    })                
                    if(result.movies){
                        let list = that.list = result.movies.list
                        let total = that.total =result.movies.total
                        that.renderer({
                            list,
                            total
                        });
                    }else{
                        let notfoundHtml = notfoundView()
                        $('ul .list').html(notfoundHtml)
                    }
                },400) 
            }
        })
        $('.cancel1').on('click',function(){
            that.render()
        })
        $('.left').on('tap',function(){
            window.history.back()
        })
        $('.cancel2').on('tap',function(){
            window.history.back()
        })
    }
}
export default new Search()